// /utils/request.js

const BASE_URL = 'http://159.75.169.224:7300/pz'

// 显示 loading
function showLoading() {
  const isShowLoading = uni.getStorageSync('isShowLoading')
  if (isShowLoading) {
    uni.hideLoading()
    uni.setStorageSync('isShowLoading', false)
  }
  uni.showLoading({
    title: '加载中...',
    complete: function () {
      uni.setStorageSync('isShowLoading', true)
    },
    fail: function () {
      uni.setStorageSync('isShowLoading', false)
    }
  })
}

// 统一请求封装
function request(option = { showLoading: false }) {
  return new Promise((resolve, reject) => {
    // 判断 url 是否存在
    if (!option.url) {
      reject(new Error('Missing URL'))
      return
    }

    if (option.showLoading) {
      showLoading()
    }

    uni.request({
      url: BASE_URL + option.url,
      data: option.data || {},
      header: option.header || {},
      method: option.method || 'GET',
      success: (response) => {
        uni.hideLoading()
        // 后端返回的数据异常
        if (response.data.code !== 10000) {
          if (option.fail && typeof option.fail === 'function') {
            option.fail(response)
          }
          reject(response)
        } else {
          if (option.success && typeof option.success === 'function') {
            option.success(response.data)
          }
          resolve(response.data)
        }
      },
      fail: (error) => {
        uni.hideLoading()
        console.error('请求失败:', error)
        reject(error)
      }
    })
  })
}

export default request